package com.shop.shop_end.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {

    public static String generateMD5(String originalString) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(originalString.getBytes());
            byte[] digest = md.digest();
            return bytesToHex(digest);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Could not find MD5 algorithm", e);
        }
    }

    public static boolean checkMD5(String originalString, String md5Hash) {
        return generateMD5(originalString).equalsIgnoreCase(md5Hash);
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }

    // Example usage
    public static void main(String[] args) {
        String originalString = "123";
        String md5Hash = generateMD5(originalString);

        System.out.println("MD5 Hash: " + md5Hash);
        boolean isValid = checkMD5(originalString, md5Hash);
        System.out.println("Is the string valid? " + isValid);
    }
}
